import winston from 'winston';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 自定义中文日志格式
const chineseFormat = winston.format.printf(({ level, message, timestamp, ip, userId, action }) => {
  let logMessage = `[${timestamp}]`;
  
  // 日志级别中文映射
  const levelMap = {
    error: '错误',
    warn: '警告',
    info: '信息',
    debug: '调试'
  };
  
  logMessage += ` [${levelMap[level] || level}]`;
  
  if (userId) {
    logMessage += ` [用户ID: ${userId}]`;
  }
  
  if (ip) {
    logMessage += ` [IP: ${ip}]`;
  }
  
  if (action) {
    logMessage += ` [操作: ${action}]`;
  }
  
  logMessage += ` ${message}`;
  
  return logMessage;
});

// 创建日志记录器
const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: winston.format.combine(
    winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
    winston.format.errors({ stack: true }),
    chineseFormat
  ),
  transports: [
    // 控制台输出
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        chineseFormat
      )
    }),
    // 错误日志文件
    new winston.transports.File({ 
      filename: path.join(__dirname, '../../logs/error.log'), 
      level: 'error',
      maxsize: 5242880, // 5MB
      maxFiles: 5
    }),
    // 所有日志文件
    new winston.transports.File({ 
      filename: path.join(__dirname, '../../logs/combined.log'),
      maxsize: 5242880,
      maxFiles: 5
    })
  ]
});

// 便捷的日志方法
export const log = {
  info: (message, meta = {}) => {
    logger.info(message, meta);
  },
  
  error: (message, meta = {}) => {
    logger.error(message, meta);
  },
  
  warn: (message, meta = {}) => {
    logger.warn(message, meta);
  },
  
  debug: (message, meta = {}) => {
    logger.debug(message, meta);
  },
  
  // 用户操作日志
  userAction: (userId, ip, action, message) => {
    logger.info(message, { userId, ip, action });
  },
  
  // 系统事件日志
  system: (message, meta = {}) => {
    logger.info(`[系统] ${message}`, meta);
  },
  
  // SSH连接日志
  ssh: (message, meta = {}) => {
    logger.info(`[SSH] ${message}`, meta);
  },
  
  // 认证日志
  auth: (message, meta = {}) => {
    logger.info(`[认证] ${message}`, meta);
  }
};

export default logger;

